#include"mystdio.h"
#include<fcntl.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
mFILE *mfopen(const char *fileno,const char *mode)
{
  int fd=-1;
  if(strcmp(mode,"r")==0)
  {
    fd=open(fileno,O_RDONLY);
  }
  else if(strcmp(mode,"w")==0)
  {
    fd=open(fileno,O_CREAT|O_WRONLY|O_TRUNC);
  }
  else if(strcmp(mode,"a")==0)
  {
    fd= open(fileno,O_CREAT|O_WRONLY|O_APPEND);
  }
  if(fd<0)
  return NULL;
  mFILE *mf=(mFILE*)malloc(sizeof(mFILE));
  if(!mf)
  {
    close(fd);
    return NULL;
  }
  mf->fileno=fd;
  mf->flag=FLUSH_LINE;
  mf->cap=SIZE;
  mf->size=0;
  return mf;
}

void mfflush(mFILE *stream)
{
  if(stream->size>0)
  {
    write(stream->fileno,stream->outbuffer,stream->size);
    //刷新到外设
    stream->size=0;
  }
}


int mfwrite(const void *ptr,int num,mFILE *stream)
{
  //拷贝
  memcpy(stream->outbuffer+stream->size,ptr,num);
  stream->size += num;
  //检测是否刷新
  if(stream->flag == FLUSH_LINE && stream->size > 0 && stream->outbuffer[stream->size-1]=='\n')
  {
    mfflush(stream);
  }
  return num;
}

void mfclose(mFILE *stream)
{
  if(stream->size >0)
  {
    mfflush(stream);
  }
  close(stream->flag);
}


